package utils;
import javax.naming.Context;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;

public class JNDITree {
	public static final String GLOBAL_CTX = "";
	public static final String JAVA_CTX = "java:";
	private static Context context = null;

	public JNDITree(Context context) throws NamingException {
		this.context = context;
	}
	
	public static void printJNDITree(String ct) throws NamingException {
		System.out.println("Printing context: "+ct);
		printJNDI(ct);
	}

	private static void printJNDI(String ct) {
		try {
			printNE(context.list(ct), ct);
		} catch (NamingException e) {}
	}

	private static void printNE(NamingEnumeration ne, String parentctx)
			throws NamingException {
		while (ne.hasMoreElements()) {
			NameClassPair next = (NameClassPair) ne.nextElement();
			printEntry(next);
			increaseIndent();
			printJNDI((parentctx.length() == 0) ? next.getName()
					: parentctx + "/" + next.getName());
			decreaseIndent();
		}
	}

	private static void printEntry(NameClassPair next) {
		System.out.println(printIndent() + next);
	}

	private static int indentLevel = 2;

	private static void increaseIndent() {
		indentLevel += 2;
	}

	private static void decreaseIndent() {
		indentLevel -= 2;
	}

	private static String printIndent() {
		StringBuffer buf = new StringBuffer(indentLevel);
		for (int i = 0; i < indentLevel; i++) {
			buf.append(" ");
		}
		return buf.toString();
	}

}
